package cn.ztr.ymcc.service.impl;

import cn.ztr.ymcc.result.JsonResult;
import cn.ztr.ymcc.service.IVerifycodeService;
import cn.ztr.ymcc.util.AssertUtil;
import cn.ztr.ymcc.feign.UserFeign;
import cn.ztr.ymcc.util.VerifyCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

@Service
@Slf4j
public class VerifycodeServiceImpl implements IVerifycodeService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserFeign userFeign;

    /**
     * 发送短信验证码
     * @param phone
     * @return
     */
    @Override
    public JsonResult sendSmsCode(String phone) {
        //1 校验手机号号格式
        boolean matches = Pattern.matches("^1[3-9]{1}[0-9]{9}$", phone);
        AssertUtil.isTrue(matches,"手机号格式错误");
        //2 校验手机号是否已注册
        JsonResult user = userFeign.findByPhone(phone);
        AssertUtil.isNull(user.getData(),"当前手机号已被注册");
        //3 验证在60秒内是否已经获取过验证
        Long expire = redisTemplate.getExpire(phone);
        if (expire!=null&&expire>240)
            return JsonResult.error("请勿频繁获取验证码");
        //4 生成验证码存入redis并设置过期时间
        Object o = redisTemplate.opsForValue().get(phone);
        String code;
        if (o!=null)
            //redis存在验证码就用上一次的验证码
            code= (String) o;
        else
            //redis不存在验证码就新生成一个验证码
            code=VerifyCodeUtils.generateVerifyCode(6);
        log.debug(code);
        redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
        return JsonResult.me("验证码已发送");

    }
}
